package com.tzx.multinetrequest

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.myapplication.network.NetworkCallback
import com.example.myapplication.network.NetworkRequestHelper
import com.tzx.multinetrequest.databinding.FragmentFirstBinding
import java.io.IOException

/**
 * 选择wifi或者蜂窝网络进行网络请求
 * 测试设备：
 * 厂商: Xiaomi
 * 型号: 2201122C
 * 系统版本: 15
 * API级别: 35
 * 测试结果：
 * 1. 当前wifi网络正常，选择Wifi网络，点击请求，请求成功
 * 2. 当前wifi网络异常，选择Wifi网络，点击请求，无任何回调。等待网络恢复后，请求成功
 * 3. 当前蜂窝网络正常，选择蜂窝网络，点击请求，请求成功
 * 4. 当前蜂窝网络异常，选择蜂窝网络，点击请求，无任何回调。等待网络恢复后，请求成功
 */
class SelectNetworkTypeFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private var transportType: Int = NetworkCapabilities.TRANSPORT_WIFI
    private var requestSuccess: Int = 0

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lookNetworkType.setOnClickListener {
            val cm: ConnectivityManager = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val content = StringBuilder()
            cm.allNetworks.forEach { network ->
                cm.getNetworkCapabilities(network)?.let { caps ->
                    if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        content.append("Wifi网络可用: $network\n")
                    } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        content.append("流量网络可用: $network\n")
                    } else {
                        content.append("其他网络可用: $network\n")
                    }
                }
            }
            binding.networkType.text = content.toString()
        }
        updateTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        binding.setNetworkWifi.setOnClickListener {
            updateTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        }
        binding.setNetworkCellular.setOnClickListener {
            updateTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        }
        binding.request.setOnClickListener {
            testRequest()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateTransportType(type: Int) {
        transportType = type
        binding.selectNetworkType.text = "当前选择的网络类型: ${if (transportType == NetworkCapabilities.TRANSPORT_WIFI) "Wifi" else "流量"}"
    }

    @SuppressLint("SetTextI18n")
    fun testRequest() {
        binding.requestContent.text = "正在请求中..."
        val helper = NetworkRequestHelper(this.requireContext())
        // 请求WiFi网络并发请求
        helper.requestNetwork(transportType, object : NetworkCallback {

            override fun onNetworkRead(network: Network) {
                Log.d("tanzhenxing22", "onNetworkRead:${Thread.currentThread().name}")
                Thread(Runnable {
                    try {
                        val response =
                            helper.makeRequestOnNetwork(network, "https://www.baidu.com")
                        binding.requestContent.post {
                            requestSuccess++
                            binding.requestContent.text = "第${requestSuccess}次请求成功\n$response"
                        }
                    } catch (e: IOException) {
                        binding.requestContent.post {
                            requestSuccess++
                            binding.requestContent.text = "exception: ${e.message}"
                        }
                    }
                }).start()
            }

            override fun onNetworkUnavailable() {
                binding.requestContent.post {
                    binding.requestContent.text = "network unavailable"
                }
            }
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}